/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package CustomerGUIs;

import Model.Bank;
import Model.CreditCard;
import Model.Customer;
import Model.InternalDBManager;
import Supermarket.AppMessages;
import Supermarket.LoginUser;
import java.awt.Window;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 *
 * @author Manolis
 */
public class NewCustomerForm extends javax.swing.JDialog {

    private final int OP_NORMAL = 0;
    private final int OP_CREDIT_CHECK = 1;
    private final int OP_CUSTOMER_PROFILE = 2;
    //ο πελάτης πάνω στον οποίο θα εργαστεί η φόρμα
    private Customer customer = new Customer();
    //μια σημαία για την ενημέρωση εγγραφής
    private boolean statusUpdate = false;
    //η πιστωτική του πελάτη
    private CreditCard creditCard = new CreditCard();
    //ο αριθμός κάρτας πόντων
    private String pointsCardNumber;
    //το τρέχων παράθυρο
    private Window thisFrame;
    //ένας entity manager
    private static EntityManager em;
    //ένας ακέραιος για 
    private int operationMode = OP_NORMAL;
    //o τρέχων χρήστης
    private LoginUser loginUser = new LoginUser();

    /**
     * Creates new form NewCustomerForm
     *
     * @param parent = η πατρική φόρμα
     * @param modal
     */
    public NewCustomerForm(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        em = InternalDBManager.getEm();
        try {
            if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
            }
        } catch (SecurityException e) {
            AppMessages.FailureMessage(this, e);
        }
        this.customer = new Customer();
        this.creditCard = new CreditCard();
        this.setIconImage(new ImageIcon(getClass().getResource("..\\Images\\cart.png")).getImage());
        initComponents();
        pointsCardNumber = makeCardNumber();
        PointsCardLabel.setText(pointsCardNumber);
        thisFrame = this;
    }

    public NewCustomerForm(java.awt.Dialog parent, boolean modal, Customer customer, CreditCard creditCard) {
        super(parent, modal);
        em = InternalDBManager.getEm();
        try {
            if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
            }
        } catch (SecurityException e) {
            AppMessages.FailureMessage(this, e);
        }
        this.customer = customer;
        this.creditCard = creditCard;
        em.merge(this.creditCard);
        this.setIconImage(new ImageIcon(getClass().getResource("..\\Images\\visa_15.png")).getImage());
        initComponents();
        //αλλάζει την επικεφαλίδα του παραθύρου
        this.setTitle("Εισαγωγή Στοιχείων Πιστωτικής κάρτας");
        //αλλάζει το text του πλήκτρου 
        this.RegisterButton.setText("Επιβεβαίωση");
        //σβήνει το εικονίδιο του
        this.RegisterButton.setIcon(null);
        CustomerDetailsToLabels(false);
        CreditCardDetailsToLabels();
        //λειτουργία ελέγχου πιστωτικής
        this.operationMode = OP_CREDIT_CHECK;
        thisFrame = this;
    }

    public NewCustomerForm(java.awt.Frame parent, boolean modal, LoginUser luser) {
        super(parent, modal);
        this.loginUser = luser;
        em = InternalDBManager.getEm();
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        //βρες τον πελάτη με βάση το userName (κάρτα πόντων)
        this.customer = (Customer) em.createNamedQuery("Customer.findByPointsCardNumber").
                setParameter("pointsCardNumber", luser.getUserName()).getSingleResult();

        this.creditCard = customer.getCreditCardList().iterator().next();

        this.setIconImage(new ImageIcon(getClass().getResource("..\\Images\\visa_15.png")).getImage());
        initComponents();
        //αλλάζει την επικεφαλίδα του παραθύρου
        this.setTitle("Τροποποίηση Προφίλ Πελάτη");
        //αλλάζει το text του πλήκτρου 
        this.RegisterButton.setText("Επιβεβαίωση");
        //σβήνει το εικονίδιο του
        this.RegisterButton.setIcon(null);
        CustomerDetailsToLabels(true);
        CreditCardDetailsToLabels();
        //λειτουργία ελέγχου πιστωτικής
        this.operationMode = OP_CUSTOMER_PROFILE;

        thisFrame = this;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        plh24_3h_ErgasiaPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("plh24_3h_ErgasiaPU").createEntityManager();
        bankQuery = java.beans.Beans.isDesignTime() ? null : plh24_3h_ErgasiaPUEntityManager.createQuery("SELECT b FROM Bank b");
        bankList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : bankQuery.getResultList();
        bankQuery1 = java.beans.Beans.isDesignTime() ? null : plh24_3h_ErgasiaPUEntityManager.createQuery("SELECT b FROM Bank b");
        bankList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : bankQuery1.getResultList();
        jPanel1 = new javax.swing.JPanel();
        FirstNameField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        LastNameField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        AddressField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        ErrorMessageLabel = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        PointsCardLabel = new javax.swing.JLabel();
        PasswordField = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        CVVField = new javax.swing.JTextField();
        BankComboBox = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        CreditCardCheckBox = new javax.swing.JCheckBox();
        CVVMissingLabel = new javax.swing.JLabel();
        CreditCardNumberMissingLabel = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        CardNumberField = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        CardHolderName = new javax.swing.JTextField();
        MissingCardOwnerNameLabel = new javax.swing.JLabel();
        PasswordMissingLabel = new javax.swing.JLabel();
        LastNameMissingLabel = new javax.swing.JLabel();
        FirstNameMissingLabel = new javax.swing.JLabel();
        CancelButton = new javax.swing.JButton();
        RegisterButton = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();

        setTitle("Εισαγωγή Νέου Πελάτη");

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        FirstNameField.setColumns(30);
        FirstNameField.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        FirstNameField.setToolTipText("");
        FirstNameField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FirstNameFieldActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel1.setText("Όνομα:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel2.setText("Επώνυμο:");

        LastNameField.setColumns(10);
        LastNameField.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel3.setText("Διεύθυνση:");

        AddressField.setColumns(50);
        AddressField.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel4.setText("Αριθμός κάρτας πόντων:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel5.setText("Password:");

        ErrorMessageLabel.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        ErrorMessageLabel.setForeground(new java.awt.Color(255, 0, 0));
        ErrorMessageLabel.setToolTipText("");

        jPanel2.setBackground(new java.awt.Color(204, 204, 204));
        jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153)));

        PointsCardLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        PointsCardLabel.setForeground(new java.awt.Color(0, 0, 153));
        PointsCardLabel.setText("XXX-XXX");
        PointsCardLabel.setToolTipText("");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(PointsCardLabel)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(PointsCardLabel))
        );

        PasswordField.setColumns(20);
        PasswordField.setToolTipText("");

        jPanel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jPanel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N

        CVVField.setColumns(20);
        CVVField.setToolTipText("");
        CVVField.setEnabled(false);

        BankComboBox.setEnabled(false);

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${resultList}");
        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, bankQuery1, eLProperty, BankComboBox);
        bindingGroup.addBinding(jComboBoxBinding);

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel6.setText("Τράπεζα:");

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel8.setText("CVV:");

        CreditCardCheckBox.setText("Εισαγωγή στοιχείων πιστωτικής κάρτας");
        CreditCardCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CreditCardCheckBoxActionPerformed(evt);
            }
        });

        CVVMissingLabel.setForeground(java.awt.Color.red);
        CVVMissingLabel.setText("    ");
        CVVMissingLabel.setToolTipText("");

        CreditCardNumberMissingLabel.setForeground(java.awt.Color.red);
        CreditCardNumberMissingLabel.setToolTipText("");

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel7.setText("Αριθμός Κάρτας:");

        CardNumberField.setColumns(50);
        CardNumberField.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        CardNumberField.setToolTipText("");
        CardNumberField.setEnabled(false);
        CardNumberField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CardNumberFieldActionPerformed(evt);
            }
        });

        jLabel12.setForeground(java.awt.Color.red);
        jLabel12.setText("    ");
        jLabel12.setToolTipText("");

        jLabel9.setText("Ονομ/νυμο Κατόχου");

        CardHolderName.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        CardHolderName.setEnabled(false);

        MissingCardOwnerNameLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        MissingCardOwnerNameLabel.setForeground(java.awt.Color.red);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(CreditCardCheckBox)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(18, 18, 18)
                                .addComponent(BankComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(32, 32, 32)
                                .addComponent(jLabel12))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(CardNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(CVVField, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(CVVMissingLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(CreditCardNumberMissingLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(CardHolderName, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(MissingCardOwnerNameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(CreditCardCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(CardHolderName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(MissingCardOwnerNameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(CVVField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CVVMissingLabel)
                    .addComponent(BankComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(CreditCardNumberMissingLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel7)
                        .addComponent(CardNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(6, 6, 6))
        );

        PasswordMissingLabel.setForeground(java.awt.Color.red);
        PasswordMissingLabel.setText("    ");
        PasswordMissingLabel.setToolTipText("");

        LastNameMissingLabel.setForeground(java.awt.Color.red);
        LastNameMissingLabel.setText("    ");
        LastNameMissingLabel.setToolTipText("");

        FirstNameMissingLabel.setForeground(java.awt.Color.red);
        FirstNameMissingLabel.setText("    ");
        FirstNameMissingLabel.setToolTipText("");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(AddressField, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(ErrorMessageLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel5)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(30, 30, 30)
                                        .addComponent(PasswordMissingLabel)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel4)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(FirstNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(FirstNameMissingLabel)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel2)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(LastNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(LastNameMissingLabel))
                                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(8, 8, 8)))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(FirstNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(LastNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(LastNameMissingLabel)
                    .addComponent(FirstNameMissingLabel))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(AddressField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel5)
                        .addComponent(PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(PasswordMissingLabel))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ErrorMessageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        CancelButton.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        CancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/cancel_16.png"))); // NOI18N
        CancelButton.setText("Ακύρωση");
        CancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelButtonActionPerformed(evt);
            }
        });

        RegisterButton.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        RegisterButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/save_16.png"))); // NOI18N
        RegisterButton.setText("Καταχώρηση");
        RegisterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RegisterButtonActionPerformed(evt);
            }
        });

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/supermarket_320.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(RegisterButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(CancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(RegisterButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(CancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel10))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void FirstNameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FirstNameFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_FirstNameFieldActionPerformed

    private void CreditCardCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CreditCardCheckBoxActionPerformed
        //αν εχει επιλεγεί το check box ενεργοποίηση εισαγωγής
        if (CreditCardCheckBox.isSelected()) {
            EnableCreditCardInput(true);
            //αλλιώς απενεργοποίηση εισαγωγής
        } else {
            EnableCreditCardInput(false);
        }
    }//GEN-LAST:event_CreditCardCheckBoxActionPerformed

    private void CardNumberFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CardNumberFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_CardNumberFieldActionPerformed

    private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelButtonActionPerformed
        if (operationMode == OP_CREDIT_CHECK) {
            this.statusUpdate = false;
            this.setVisible(false);
        } else {
            this.dispose();
        }
    }//GEN-LAST:event_CancelButtonActionPerformed

    private void RegisterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RegisterButtonActionPerformed
        //Σβήνουμε τυχόν μηνύματα λάθους (labels)
        initLabels();
        //αν η λειτουργία είναι έλεγχος πιστωτικής κάρτας
        if (operationMode == OP_CREDIT_CHECK) {
            //αν τα στοιχεία της κάρτας είναι στη σωστή μορφή
            if (registerCreditCard()) {
                //κάνε τη φόρμα αόρατη ώστε να περαστούν τα στοιχεία
                this.statusUpdate = true;
                this.setVisible(false);
            }
            //αν η λειτουργία είναι μεταβολή προφίλ πελάτη
        } else if (operationMode == OP_CUSTOMER_PROFILE) {
            if (registerCreditCard() && registerCustomer()) {
                em.merge(customer);
                em.merge(creditCard);
                em.getTransaction().commit();
                this.dispose();
            }
            //αν η μεταφορά και αποθήκευση έγινε κανονικά κλείσιμο της φόρμας
        } else if (statusUpdate = DataManager()) {
            this.dispose();
        }

    }//GEN-LAST:event_RegisterButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewCustomerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                NewCustomerForm dialog = new NewCustomerForm(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField AddressField;
    private javax.swing.JComboBox BankComboBox;
    private javax.swing.JTextField CVVField;
    private javax.swing.JLabel CVVMissingLabel;
    private javax.swing.JButton CancelButton;
    private javax.swing.JTextField CardHolderName;
    private javax.swing.JTextField CardNumberField;
    private javax.swing.JCheckBox CreditCardCheckBox;
    private javax.swing.JLabel CreditCardNumberMissingLabel;
    private javax.swing.JLabel ErrorMessageLabel;
    private javax.swing.JTextField FirstNameField;
    private javax.swing.JLabel FirstNameMissingLabel;
    private javax.swing.JTextField LastNameField;
    private javax.swing.JLabel LastNameMissingLabel;
    private javax.swing.JLabel MissingCardOwnerNameLabel;
    private javax.swing.JTextField PasswordField;
    private javax.swing.JLabel PasswordMissingLabel;
    private javax.swing.JLabel PointsCardLabel;
    private javax.swing.JButton RegisterButton;
    private java.util.List<Model.Bank> bankList;
    private java.util.List<Model.Bank> bankList1;
    private javax.persistence.Query bankQuery;
    private javax.persistence.Query bankQuery1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.persistence.EntityManager plh24_3h_ErgasiaPUEntityManager;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    //μέθοδος που αναλαμβάνει να αποθηκεύσει τα δεδομένα της φόρμας
    public boolean DataManager() {
        //αν τα στοιχεία του πελάτη δεν είναι στη σωστή μορφή επιστροφή
        if (!registerCustomer()) {
            return false;
        }
        //εφόσον υπάρχει ήδη στη ΒΔ μήνυμα λάθους και επιστροφή
        if (isCustomerInDB()) {
            JOptionPane.showMessageDialog(thisFrame,
                    AppMessages.CustomerExistsMsg, AppMessages.DBMsg, JOptionPane.ERROR_MESSAGE);
            return false;
        }
        //Εχουμε πελάτη με σωστά στοιχεία ο οποίος δεν υπάρχει στη ΒΔ
        //Αν δεν έχει γίνει εισαγωγή πιστωτικής κάρτας
        if (!CreditCardCheckBox.isSelected()) {
            //πρόσθεσε τον πελάτη στη ΒΔ
            if (AddCustomerToDB()) {
                return true;
            }
            //αν έχει γίνει εισαγωγή και τα στοιχεία είναι στη σωστή μορφή
        } else if (registerCreditCard()) {
            //πρόσθεσε πελάτη και κάρτα στη ΒΔ
            if (AddBothToDB()) {
                return true;
            }
        }
        return false;
    }

    //έλεγχος και μεταφορά των πεδίων της φόρμας σε αντικείμενο customer
    //για την καταχώρηση στη βάση.
    public boolean registerCustomer() {
        boolean success = true;
        //Έλεγχος εισαγωγής ονόματος πελάτη
        if (FirstNameField.getText().isEmpty()) {
            ErrorMessageLabel.setText(AppMessages.FieldsMissingMsg);
            FirstNameMissingLabel.setText("(*)");
            success = false;
        } else {
            customer.setFirstName(FirstNameField.getText());
        }
        //Έλεγχος εισαγωγής επώνυμου πελάτη
        if (LastNameField.getText().isEmpty()) {
            ErrorMessageLabel.setText(AppMessages.FieldsMissingMsg);
            LastNameMissingLabel.setText("(*)");
            success = false;
        } else {
            customer.setLastName(LastNameField.getText());
        }
        if (AddressField.getText().isEmpty()) {
            customer.setAddress(null);
        } else {
            customer.setAddress(AddressField.getText());
        }
        //Έλεγχος εισαγωγής κωδικού πελάτη
        if (PasswordField.getText().isEmpty()) {
            ErrorMessageLabel.setText(AppMessages.FieldsMissingMsg);
            PasswordMissingLabel.setText("(*)");
            success = false;
        } else {
            customer.setPassword(PasswordField.getText());
        }
        customer.setPointsCardNumber(PointsCardLabel.getText());
        if (!this.loginUser.getUserType().equals("Customer")) {
            customer.setAvailablePoints(0);
        }
        //επέστρεψε το αποτέλεσμα της μεταφοράς δεδομένων
        return success;
    }

    //δημιουργία αριθμού κάρτας πόντων
    private String makeCardNumber() {
        //έναρξη δοσοληψιών
        try {
            if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
            }
        } catch (SecurityException e) {
            AppMessages.FailureMessage(this, e);
        }
        //ένα string για τον αριθμό κάρτας πόντων
        String cardNumber;
        //όσο ο αριθμός θα εντοπίζεται στη ΒΔ
        while (true) {
            //Δημιουργία αριθμού κάρτας
            Random rn = new Random();
            cardNumber = "" + rn.nextInt(9) + rn.nextInt(10) + rn.nextInt(10) + "-"
                    + rn.nextInt(10) + rn.nextInt(10) + rn.nextInt(10);
            try {
                //έλεγχος ύπαρξης κάρτας στη ΒΔ
                Customer customers_card = (Customer) em.createNamedQuery("Customer.findByPointsCardNumber")
                        .setParameter("pointsCardNumber", cardNumber).getSingleResult();
                //αν η λίστα είναι κενή - δεν έχει βρεθεί ο αριθμός κάρτας
            } catch (NoResultException e) {
                System.out.print(e);
                break;
            }
        }
        return cardNumber;
    }

    //Πρόσθήκη πελάτη στη ΒΔ
    private boolean AddCustomerToDB() {
        try {
            if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
            }
            em.persist(customer);
            em.getTransaction().commit();
            //Εμφανίζει μήνυμα επιτυχίας
            AppMessages.SuccessMessage(thisFrame);
            return true;
        } catch (SecurityException e) {
            AppMessages.FailureMessage(thisFrame, e);
            em.getTransaction().rollback();
            return false;
        }
    }

    //Πρόσθεσε την πιστωτική κάρτα στη ΒΔ
    private boolean AddBothToDB() {
        try {
            if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
            }
            //ενημερώνει πίνακες συσχετίσεων
            creditCard.addCustomerToCustomerList(customer);
            customer.addCardToCreditCardList(creditCard);
            //ενημερώνει αρχεία
            em.persist(creditCard);
            em.persist(customer);
            //γράφει στη ΒΔ
            em.getTransaction().commit();
            //εμφανίζει μήνυμα επιτυχίας
            AppMessages.SuccessMessage(thisFrame);
            return true;
        } catch (SecurityException e) {
            AppMessages.FailureMessage(thisFrame, e);
            em.getTransaction().rollback();
            return false;
        }
    }

    //έλεγχος εισαγωγής πεδίων πιστωτικής κάρτας και
    //ανάθεση σε αντικείμενο CreditCard
    public boolean registerCreditCard() {
        boolean success = true;
        String Card_Owner, CVV, pk_number;
        Card_Owner = CardHolderName.getText();
        if (Card_Owner == null) {
            ErrorMessageLabel.setText(ErrorMessageLabel.getText().toString() + AppMessages.FieldsMissingMsg);
            MissingCardOwnerNameLabel.setText("(*)");
            success = false;
        } else {
            creditCard.setOwnerName(Card_Owner);
        }
        if (BankComboBox.getSelectedIndex() < 0) {
            success = false;
        } else {
            //αποθηκεύει την επιλογή τράπεζας
            Bank bank = (Bank) BankComboBox.getSelectedItem();
            creditCard.setBank(bank);
            bank.addCreditCardToCreditCardList(creditCard);
        }
        //έλεγχος CVV
        CVV = checkAndConvertCVV();
        if (CVV == null) {
            ErrorMessageLabel.setText(ErrorMessageLabel.getText().toString() + AppMessages.BadCvvMsg);
            CVVMissingLabel.setText("999");
            success = false;
        } else {
            this.creditCard.setCvv(CVV);
        }
        //έλεγχος ορθότητας αριθμού πιστωτικής κάρτας
        pk_number = checkAndConvertPknumber();
        if (pk_number == null) {
            CreditCardNumberMissingLabel.setText("9999-999999-9999");
            ErrorMessageLabel.setText(ErrorMessageLabel.getText().toString() + AppMessages.BadCardNumberMsg);
            success = false;
        } else {
            this.creditCard.setPkNumber(pk_number);
        }

        return success;
    }

    //έλεγχος του CVV με χρήση pattern. Επιστρέφει τον CVV ή NULL αν δεν είναι έγκυρος.
    private String checkAndConvertCVV() {
        //μορφή κωδικού 999 (3 αριθμητικά ψηφία)
        Pattern pk = Pattern.compile("\\d\\d\\d");
        //σύγκριση παττερν με το πεδίο CVV
        Matcher m = pk.matcher(CVVField.getText());
        boolean success = m.matches();
        //αν είναι επιτυχής επέστρεψε CVV αλλιώς null
        return (success ? CVVField.getText() : null);
    }

    //Έλεγχος του αριθμού κάρτας με χρήση pattern.
    //Επιστρέφει τον αριθμό πιστωτικής ή null αν δεν είναι έγκυρος.
    private String checkAndConvertPknumber() {
        //ορίζουμε το επιτρεπόμενο pattern 9999-999999-9999
        Pattern pk = Pattern.compile("\\d\\d\\d\\d\\-\\d\\d\\d\\d\\d\\d\\-\\d\\d\\d\\d");
        //συγκρίνουμε το πεδίο με το  pattern
        Matcher m = pk.matcher(CardNumberField.getText());
        //αν ταιριάζουν τότε ο matcher επιστρέφει true
        boolean success = m.matches();
        //αν είναι επιτυχής επέστρεψε αριθμό κάρτας αλλιώς null
        return (success ? CardNumberField.getText() : null);
    }

    //μέθοδος που αρχικοποιεί όλα τα labels που χρησιμοποιούνται
    //για την εμφάνιση μηνυμάτων
    private void initLabels() {
        ErrorMessageLabel.setText("");
        FirstNameMissingLabel.setText("");
        LastNameMissingLabel.setText("");
        PasswordMissingLabel.setText("");
        CVVMissingLabel.setText("");
        CreditCardNumberMissingLabel.setText("");
        MissingCardOwnerNameLabel.setText("");
    }

    //boolean μέθοδος που ελέγχει αν ο πελάτης υπάρχει στη ΒΔ
    private boolean isCustomerInDB() {
        try {
            if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
            }
            //ψάχνει πελάτη με όνομα και επίθετο
            Customer customers_exists = (Customer) em.createNamedQuery("Customer.findByFirstAndLastName")
                    .setParameter("firstName", customer.getFirstName())
                    .setParameter("lastName", customer.getLastName()).getSingleResult();
            //αν βρεθεί επιστρέφει true
            return true;
        } catch (NoResultException e) {
            //αν δε βρεθεί επιστρέφει false
            return false;
        }
    }

    //ενεργοποιεί ή απενεργοποιεί την εισαγωγή πιστωτικής κάρτας
    private void EnableCreditCardInput(boolean b) {
        CardNumberField.setEnabled(b);
        CVVField.setEnabled(b);
        BankComboBox.setEnabled(b);
        //Αν το πεδίο ενεργοποιείται και είναι κενό
        if (b && CardHolderName.getText().equals("")) {
            //συνένωση ονόματος και επιθέτου πελάτη (προσυμπλήρωση)
            CardHolderName.setText(FirstNameField.getText() + " " + LastNameField.getText());
        }
        CardHolderName.setEnabled(b);
    }

    //επιστρέφει την επιτυχία της εισαγωγής νέου πελάτη
    public boolean getStatusUpdate() {
        return this.statusUpdate;
    }

    //επιστρέφει τον νέο πελάτη
    public Customer getData() {
        return this.customer;
    }

    //γαμίζει τα πεδία με τα στοιχεία πελάτη
    private void CustomerDetailsToLabels(boolean b) {
        FirstNameField.setText(customer.getFirstName());
        FirstNameField.setEnabled(b);
        LastNameField.setText(customer.getLastName());
        LastNameField.setEnabled(b);
        AddressField.setText(customer.getAddress());
        AddressField.setEnabled(b);
        PasswordField.setText(customer.getPassword());
        PasswordField.setEnabled(b);
        PointsCardLabel.setText(customer.getPointsCardNumber());
        PointsCardLabel.setEnabled(b);
    }

    //γεμίζει τα πεδία με τα στοιχεία πιστωτικής
    private void CreditCardDetailsToLabels() {
        CreditCardCheckBox.setSelected(true);
        //αν η κάρτα υπάρχει
        if (!creditCard.getCustomerList().isEmpty()) {
            CardNumberField.setText(creditCard.getPkNumber());
            CVVField.setText(creditCard.getCvv());
            BankComboBox.setEnabled(true);
            //ρύθμισε το comboBox ώστε να δείχνει τη σωστή τράπεζα
            BankComboBox.setSelectedIndex(creditCard.getBank().getBankId() - 1);
            CardHolderName.setText(creditCard.getOwnerName());
        }
        EnableCreditCardInput(true);
    }

    //επιστρέφει την πιστωτική του Πελάτη
    public CreditCard getCreditCard() {
        return this.creditCard;
    }

}
